const article = require("../service/article");
const ApiResult = require("../common/ApiResult");
const Enum = require("../enum");

module.exports = {
  /**
   * 需要做权限管理
   * @param ctx
   * @return {Promise<void>}
   */
  getList: async function(ctx) {
    const { currentPage = 1, pageSize = 10, title, state } = ctx.query;
    if (!(+currentPage && +pageSize)) {
      ctx.body = ApiResult.ERROR(Enum.PARAM_ERROR);
      return;
    }
    const rep = await article.selectByPage({
      currentPage,
      pageSize,
      title,
      state
    });
    if ("data" in rep) {
      ctx.body = ApiResult.SUCCESS(rep.data);
      return;
    }
    ctx.body = ApiResult.ERROR(rep.message);
  },
  save: async function(ctx) {
    const _article = ctx.request.body;
    if (_article && Object.keys(_article).length) {
      // 查询
      try {
        await article.insertOrUpdate(_article);
        ctx.body = ApiResult.SUCCESS();
      } catch (e) {
        ctx.body = ApiResult.ERROR();
      }
    } else {
      ctx.body = ApiResult.ERROR(Enum.PARAM_ERROR);
    }
  },
  query: async function(ctx) {
    const { id } = ctx.request.body;
    if (id) {
      // 查询
      try {
        const { data } = await article.selectById(id);
        ctx.body = ApiResult.SUCCESS(data);
      } catch (e) {
        ctx.body = ApiResult.ERROR();
      }
    } else {
      ctx.body = ApiResult.ERROR(Enum.PARAM_ERROR);
    }
  },
  getListByWeb: async function(ctx) {
    const { currentPage = 1, pageSize = 10, title } = ctx.query;
    const state = "publish";
    if (!(+currentPage && +pageSize)) {
      ctx.body = ApiResult.ERROR(Enum.PARAM_ERROR);
      return;
    }
    const rep = await article.selectByPage(
      { currentPage, pageSize, title, state },
      true
    );
    if ("data" in rep) {
      ctx.body = ApiResult.SUCCESS(rep.data);
      return;
    }
    ctx.body = ApiResult.ERROR(rep.message);
  }
};
